﻿using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.Utilities;
using System.Web;
using System.Web.UI;
using System.Text;

namespace ConsultPoint.SharePoint.RibbonVisibility.Layouts
{
    public partial class RibbonVisibilitySettings : LayoutsPageBase
    {
       
        SPWeb _web = null;

        #region Properties
        private String SelectedValue
        {
            get
            {
                //inherits
                if (rdoInherits.Checked)
                    return Helper.Constants.INHERITS;

                //always visible
                if (lstVisibilityRule.SelectedValue == "ALWAYS")
                    return Helper.Constants.ALWAYS;

                //never visible
                if (lstVisibilityRule.SelectedValue == "NEVER")
                    return Helper.Constants.NEVER;

                //conditional
                StringBuilder builder = new StringBuilder();
                builder.AppendFormat("{0};", chkAnonymous.Checked.ToString());
                builder.AppendFormat("{0};", lstRule.SelectedValue);
                builder.AppendFormat(peoplePicker.CommaSeparatedAccounts);
                return builder.ToString();
            }

        }
        
        private string RedirectUrl
        {
            get
            {
                if (Request.QueryString["Source"] != null)
                    return Request.QueryString["Source"];
                return String.Empty;
            }
        }
        private SPWeb CurrentSPWeb
        {
            get
            {
                return SPContext.Current.Web;
            }
        }
        
        #endregion

        #region override
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                _web = CurrentSPWeb;
                if (!IsPostBack)
                {
                    ApplyInitialValue();
                    rdo_CheckedChanged(this, EventArgs.Empty);
                    lstVisibilityRule_SelectedIndexChanged(this, EventArgs.Empty);
                }
            }
            catch (Exception ex)
            {
                this.Controls.Clear();
                this.Controls.Add(new LiteralControl("Error : " + ex.Message));
            }
        }
        protected override void OnInit(EventArgs e)
        {
            this.rdoOverwrite.CheckedChanged += new EventHandler(rdo_CheckedChanged);
            this.rdoInherits.CheckedChanged += new EventHandler(rdo_CheckedChanged);
            this.btnCancel.Click += new EventHandler(btnCancel_Click);
            this.btnSave.Click += new EventHandler(btnSave_Click);
            this.lstVisibilityRule.SelectedIndexChanged += new EventHandler(lstVisibilityRule_SelectedIndexChanged);
        }

        
        public override void Dispose()
        {
            if (_web != null)
                _web.Dispose();
        }
        #endregion override

        #region Event Handlers
        void btnSave_Click(object sender, EventArgs e)
        {
            ApplyValue(_web, SelectedValue, chkApplyToChildren.Checked);
            DoRedirect();
        }
        void btnCancel_Click(object sender, EventArgs e)
        {
            DoRedirect();
        }
        void rdo_CheckedChanged(object sender, EventArgs e)
        {
            divParameters.Visible = rdoOverwrite.Checked;
        }
        void lstVisibilityRule_SelectedIndexChanged(object sender, EventArgs e)
        {
            divConditional.Visible = lstVisibilityRule.SelectedValue == "CONDITION";
        }
        #endregion Event Handlers

        #region Private
        private string GetValues()
        {
            if (_web.Properties.ContainsKey(Helper.Constants.KEY))
                return _web.Properties[Helper.Constants.KEY];
            else
                return String.Empty;
        }
        void ApplyInitialValue()
        {
            string values = GetValues();
            if (string.IsNullOrEmpty(values))
            {
                rdoInherits.Checked = true;
                return;
            }
            
            //inherits
            if (values == Helper.Constants.INHERITS)
            {
                rdoInherits.Checked = true;
                return;
            }

            //overwrite
            rdoOverwrite.Checked = true;
            //always or never
            if (values == Helper.Constants.ALWAYS || values == Helper.Constants.NEVER)
            {
                lstVisibilityRule.ClearSelection();
                lstVisibilityRule.Items.FindByValue(values).Selected = true;
                return;
            }

            if (_web.Properties.ContainsKey(Helper.Constants.KEY_COLLAPSE))
                ChkCollapseFreeSpace.Checked = Boolean.Parse(_web.Properties[Helper.Constants.KEY_COLLAPSE]);

            //conditional
            lstVisibilityRule.ClearSelection();
            lstVisibilityRule.Items.FindByValue("CONDITION").Selected = true;
 
            chkAnonymous.Checked = Boolean.Parse(values.Split(';')[0]);
           
            lstRule.ClearSelection();
            lstRule.Items.FindByValue(values.Split(';')[1]).Selected = true;
            
            peoplePicker.CommaSeparatedAccounts = values.Split(';')[2];
            peoplePicker.Validate();
            
        }
        void DoRedirect()
        {
            if (RedirectUrl != String.Empty)
                SPUtility.Redirect(RedirectUrl, SPRedirectFlags.Default, HttpContext.Current);
            else
                SPUtility.Redirect(SPContext.Current.Web.Url + "/_layouts/settings.aspx" , SPRedirectFlags.Default, HttpContext.Current);
        }
        void ApplyValue(SPWeb web, string value, bool recursive)
        {
            bool allowunsafe = _web.AllowUnsafeUpdates;
            web.AllowUnsafeUpdates = true;
            try
            {
                string accountid = SelectedValue;
                if (web.Properties.ContainsKey(Helper.Constants.KEY))
                    web.Properties[Helper.Constants.KEY] = value;
                else
                    web.Properties.Add(Helper.Constants.KEY, value);

                if (web.Properties.ContainsKey(Helper.Constants.KEY_COLLAPSE))
                    web.Properties[Helper.Constants.KEY_COLLAPSE] = ChkCollapseFreeSpace.Checked.ToString();
                else
                    web.Properties.Add(Helper.Constants.KEY_COLLAPSE, ChkCollapseFreeSpace.Checked.ToString());

                web.Properties.Update();
            }
            finally
            {
                web.AllowUnsafeUpdates = allowunsafe;
            }

            if (recursive)
                foreach (SPWeb subweb in web.Webs)
                    ApplyValue(subweb, Helper.Constants.INHERITS, recursive);
        }
        #endregion

    }
}
